package com.xiaoshuai.userListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.xiaoshuai.po.User;
import com.xiaoshuai.service.UseService;

import java.util.ArrayList;

/**
 * @Author 小帅
 * @Description 自定义检测器读数据
 * @Date 2025/4/2
 **/
public class UserListener implements ReadListener<User> {

    private static final int BATCH_COUNT = 100;
    private ArrayList<User> list = new ArrayList<User>(BATCH_COUNT);
    private UseService useService;

    public UserListener(UseService useService) {
        this.useService = useService;
    }

    //每读一行数据就会调用这个方法
    @Override
    public void invoke(User user, AnalysisContext analysisContext) {
        //将读取到的一行数据添加到集合
        list.add(user);
        //判断如果读取的数据大于等于100条就进行批量插入
        if (list.size() >= BATCH_COUNT) {
            useService.saveBatch(list);
            //清除缓存
            list = new ArrayList<User>();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (list.size() > 0) {
            //操作数据库
            useService.saveBatch(list);
            //清除缓存
            list = new ArrayList<User>();
        }
    }
}
